package cn.tedu.csmall.passport.service.impl;

import cn.tedu.csmall.passport.pojo.dto.AdminLoginDTO;
import cn.tedu.csmall.passport.service.IAdminService;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Header;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@Service
public class AdminServiceImpl implements IAdminService {

    //Token中的密钥
    String secreKey="sadasdasdasdasd";

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public String login(AdminLoginDTO adminLoginDTO) {

        // 创建被认证数据
        Authentication authentication
                = new UsernamePasswordAuthenticationToken(
                        adminLoginDTO.getUsername(), adminLoginDTO.getPassword());
        // 执行认证，如果认证失败，将抛出异常
        Authentication authenticate = authenticationManager.authenticate(authentication);

        // 如果程序可执行到此处，则表示认证成功
        User user=(User) authenticate.getPrincipal();
        Map<String ,  Object> claims=new HashMap<>();
        claims.put("username",user.getUsername());
        claims.put("permissions", JSON.toJSONString(user.getAuthorities()));

        JwtBuilder builder = Jwts.builder();
        // header, claims (payload), signature
        String jwt=builder.setHeaderParam(Header.TYPE,Header.JWT_TYPE)
                .setHeaderParam(Header.CONTENT_TYPE,"HS256")
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis()+5*60*60*1000))
                .signWith(SignatureAlgorithm.HS256,secreKey)
                .compact();
         log.debug("返回JWT数据:{}",jwt);
        return jwt;
    }

}
